package com.travel.core;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.mysql.cj.jdbc.MysqlDataSource;

/**
 * JDBC配置数据源，建立及释放连接
 *
 * @author SAGITTAR
 */
abstract class BaseDataSource {

    private static final Logger LOGGER = LogManager.getLogger(BaseDataSource.class);

    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    static {
        Properties properties = new Properties();
        try {
            properties.load(BaseDataSource.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            Class.forName(properties.getProperty("driverName"));
        } catch (IOException | ClassNotFoundException e) {
            LOGGER.error(e.getLocalizedMessage(), e);
        }
        URL = properties.getProperty("url");
        USERNAME = properties.getProperty("userName");
        PASSWORD = properties.getProperty("password");
    }

    /**
     * 获取MySQL数据源
     *
     * @return
     */
    protected static DataSource getMysqlDataSource() {
        LOGGER.debug("获取MySQL数据源");
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USERNAME);
        mysqlDataSource.setPassword(PASSWORD);
        return mysqlDataSource;
    }
}
